<?php
namespace App\Utility;


use AlibabaCloud\Client\AlibabaCloud;
use EasySwoole\EasySwoole\Config;

class Alisms{

    //短信配置
    protected $config;
    public function __construct(){
        $this->config = Config::getInstance()->getConf('ALISMS');
    }


    /**
     * test 发送
     * try{
     *     $sms = new Alisms();
     *     $url = $sms->send('13667635645','SMS_163525395');
     *     return $this->writeJson(0,$url);
     * }catch (\Throwable $e){
     *     return $this->writeJson(1,null,$e->getMessage());
     * }
     * @param string $mobile
     * @param string $tempCode
     * @return bool
     * @throws \AlibabaCloud\Client\Exception\ClientException
     * @throws \AlibabaCloud\Client\Exception\ServerException
     */
    //发送短信
    public function send(string $mobile,string $tempCode){
        if(empty($mobile) || empty($tempCode)){
            throw new \Exception('手机号或者短信模板CODE不能为空');
        }
        AlibabaCloud::accessKeyClient($this->config['accessKeyId'], $this->config['accessKeySecret'])
            ->regionId($this->config['region'])
            ->asGlobalClient();
        $result = AlibabaCloud::rpcRequest()
            ->product('Dysmsapi')
            ->version('2017-05-25')
            ->action('SendSms')
            ->method('POST')
            ->options(['query' => [
                    'RegionId' => $this->config['region'],
                    'PhoneNumbers' => $mobile,
                    'SignName' => $this->config['sign'],
                    'TemplateParam' => $this->getParams($tempCode),
                    'TemplateCode' => $tempCode,
                ]])->request()->toArray();
        if($result['Code'] == 'OK' && $result['Message'] == 'OK'){
            return true;
        }else{
            throw new \Exception($result['Message']);
        }
    }

    //获取6位数验证码
    protected function getCode(){
        $char = '0123456789';
        $code = '';
        for ($i = 0; $i < 6; $i++) {
            $code .= $char[mt_rand(0, strlen($char) - 1)];
        }
        return $code;
    }

    //获取短信发送内容
    protected function getParams(string $tempCode){
        $params = [];
        switch($tempCode){
            case 'SMS_163525395':
                $params = ['status' => $this->getCode(),'remark'=>'WX2019041297555598'];
                break;
            case 'SMS_163620598':
                $params = ['code'=> $this->getCode()];
                break;
        }
        return json_encode($params);
    }

}